package com.zdpx.pxframework.database;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.zdpx.pxframework.core.factory.YamlPropertySourceFactory;
import com.zdpx.pxframework.database.config.DruidProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.Resource;

/**
 * Druid自动配置类
 *
 * @Description:
 * @Author: Cheng XiaoXiao
 * @Date: 2022/5/17 13:56
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({DruidProperties.class})
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:druid-default.yml")
public class DruidAutoConfiguration {

    @Resource
    DruidProperties druidProperties;

    /**
     * 注册druid的servlet
     *
     * @return servletBean
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> druidServlet() {
        log.info("init Druid Servlet Configuration ...");
        ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(), "/druid/*");

        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", druidProperties.getUserName());
        servletRegistrationBean.addInitParameter("loginPassword", druidProperties.getPassword());
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 注册防火墙过滤器
     *
     * @return 过滤器注册实体
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> filterRegistrationBean() {
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
